package com.wuseguang.springcloud.dao.jdbc;

import com.wuseguang.springcloud.JdbcTemplate.BaseTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;

@Repository
public class AttendJdbc extends BaseTemplate {
    private Logger logger = LoggerFactory.getLogger(this.getClass());


    public int updateAttendGroup(String listSql, String classids, Integer id) {
        try {
            String[] split = classids.split(",");
            return dao.batchUpdate(listSql, new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    String s = split[i];
                    logger.info("updateAttendGroup()，classids={}", classids);
                    ps.setString(1, s);
                    ps.setInt(2, id);
                }

                @Override
                public int getBatchSize() {
                    return split.length;
                }
            }).length;
        } catch (Exception e) {
            logger.info("批量添加异常,error={}", e);
            ;// 手动回滚
        }
        return 0;
    }



    public int updateAttendGroupUser(String listSql, String userids, Integer id) {
        try {
            logger.info("updateAttendGroupUser,userids={},groupid={}", userids, id);
            String sql = " DELETE FROM attendance_group_user WHERE attend_group_id=? ";
            updateByParameter(sql, id);
            String[] split = userids.split(",");
            return dao.batchUpdate(listSql, new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    String s = split[i];
                    ps.setInt(1, Integer.parseInt(s));
                    ps.setInt(2, id);
                }

                @Override
                public int getBatchSize() {
                    return split.length;
                }
            }).length;
        } catch (Exception e) {
            logger.info("批量添加异常,error={}", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();// 手动回滚
        }
        return 0;
    }


    public Map<String, Map<String, String>> getMapShift(String sql) {
        return dao.query(sql, rs -> {
            Map<String, Map<String, String>> maps = new HashMap<String, Map<String, String>>();
            while (rs.next()) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("type", rs.getString("type"));//考勤类型:0 1天1次、1 1天2次
                map.put("starttime", rs.getString("starttime"));
                map.put("endtime", rs.getString("endtime"));
                map.put("starttime1", rs.getString("starttime1"));
                map.put("endtime1", rs.getString("endtime1"));
                maps.put(rs.getString("id"), map);
            }
            logger.info("AttendJdbc==>getMapShift,maps={}", maps.toString());
            return maps;
        });
    }

    public Map<String, Object> queryAttendListMap1(String sql, Object... args) {
        logger.info("AttendJdbc==>queryAttendListMap,sql={}", sql);
        return dao.query(sql, args, rs -> {
            Map<String, Object> maps = new HashMap<String, Object>();
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            Set<Integer> set = new HashSet<Integer>();
            while (rs.next()) {
                //d.userid tid,d.attend_group_id,d.shift_id,d.attendtime,d.attendtype
                Map<String, Object> map = new HashMap<String, Object>();
                int tid = rs.getInt("tid");
                map.put("tid", tid);
                map.put("attend_group_id", rs.getString("attend_group_id"));
                map.put("shift_id", rs.getString("shift_id"));
                map.put("attendtime", rs.getString("attendtime"));
                map.put("attendtype", rs.getString("attendtype"));
                list.add(map);
                set.add(tid);
            }
            maps.put("list", list);
            maps.put("set", set);
            logger.info("AttendJdbc==>queryAttendListMap,maps={}", maps.toString());
            return maps;
        });
    }


    public List<Map<String, Object>> queryAttendListMap(String sql, Object... args) {
        logger.info("AttendJdbc==>queryAttendListMap,sql={}", sql);
        return dao.query(sql, args, rs -> {
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            while (rs.next()) {
                Map<String, Object> map = new HashMap<String, Object>();
                int tid = rs.getInt("tid");
                map.put("tid", tid);
                map.put("attend_group_id", rs.getString("attend_group_id"));
                map.put("shift_id", rs.getString("shift_id"));
                map.put("attendtime", rs.getString("attendtime"));
                map.put("attendtype", rs.getString("attendtype"));
                list.add(map);
            }
            logger.info("AttendJdbc==>queryAttendListMap,maps={}", list.toString());
            return list;
        });
    }

    public List<Map<String, Object>> queryAttendGroupListMap(String sql, Object... args) {
        String sql1 = "SELECT type,starttime,endtime,starttime1,endtime1 FROM  attendance_shift WHERE id=?";
        String sql2 = "SELECT GROUP_CONCAT(s.name) string FROM attendance_group_classid d,classes s WHERE d.attend_group_id=? AND d.class_id=s.id ";
        logger.info("AttendJdbc==>queryAttendListMap,sql={}", sql);
        return dao.query(sql, args, rs -> {
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            while (rs.next()) {
                Map<String, Object> map = new HashMap<String, Object>();
                int id = rs.getInt("id");
                map.put("id", id);
                String s = queryString(sql2, id);
                map.put("classnames", s);
                map.put("name", rs.getString("name"));
                map.put("count", rs.getString("count"));
                map.put("attendtype", rs.getString("attendtype"));
                String shift_id = rs.getString("shift_id");
                if (StringUtils.isEmpty(shift_id)) {
                    map.put("shift", "");
                } else {
                    StringBuilder stringBuilder = new StringBuilder();
                    String[] split = shift_id.split(",");
                    for (int i = 0; i < split.length; i++) {
                        String s1 = split[i];
                        if ("0".equals(s1)) {
                            stringBuilder.append(getWeeks(i)).append(": 休息 ");
                        } else {
                            Map<String, Object> mapList = null;
                            try {
                                mapList = queryMap(sql1, s1);
                            } catch (Exception e) {
                                logger.info("queryAttendGroupAll-->mapList,error={}", e);
                            }
                            if (mapList != null) {
                                Object starttime = mapList.get("starttime");
                                Object endtime = mapList.get("endtime");
                                Object starttime1 = mapList.get("starttime1");
                                Object endtime1 = mapList.get("endtime1");
                                stringBuilder.append(getWeeks(i)).append(": 考勤班次 ");
                                Integer type = (Integer) mapList.get("type");
                                if (type == 0) {
                                    stringBuilder.append(starttime).append("-").append(endtime1).append(" 中午休息时间: ").append(endtime).append("-").append(starttime1).append("  ");
                                } else {
                                    stringBuilder.append(starttime).append("-").append(endtime).append(",").append(starttime1).append("-").append(endtime1).append("  ");
                                }
                            }
                        }
                        map.put("shift", stringBuilder.toString());
                    }
                }
                list.add(map);
            }
            logger.info("AttendJdbc==>queryAttendGroupListMap,maps={}", list.toString());
            return list;
        });
    }

    public String getWeeks(int s) {
        String week = "";
        if (s == 0) {
            week = "周一";
        } else if (s == 1) {
            week = "周二";
        } else if (s == 2) {
            week = "周三";
        } else if (s == 3) {
            week = "周四";
        } else if (s == 4) {
            week = "周五";
        } else if (s == 5) {
            week = "周六";
        } else if (s == 6) {
            week = "周日";
        }
        return week;
    }
}
